SHELL := /bin/bash
BD = bin
SD = src
CD = cases
case := $(shell ls $(CD)) 
casedirs := $(foreach dir,$(case),$(CD)/$(dir)/run)
casefiles := $(foreach dir,$(casedirs),$(dir)/sam.std)
checkfiles := $(foreach dir,$(casedirs),$(dir)/../check/sam.std)
checks := $(foreach dir,$(casedirs),$(dir)/../check/compare)

.PHONY = clean compile run updateChecks check

clean: 
	rm -f $(BD)/*
	find . -name '*~' -delete
	rm -rf _tmp
	rm -f $(checks)
	rm -rf $(casedirs)

compile: $(BD)/sam
$(BD)/sam: $(SD)/sam.tpl
	mkdir _tmp
	cp $(SD)/$(<F) $(SD)/*.h _tmp
	cd _tmp; admb -r -s $(<F)
	cp _tmp/sam $(BD)
	rm -rf _tmp
	mkdir $(casedirs)

run: $(casefiles)
$(casefiles): $(BD)/sam
	cp $(BD)/sam $(@D)
	cp $(@D)/../data/* $(@D)
	cp $(@D)/../conf/* $(@D)
	cd $(@D); ./sam -noinit -nr 2
	cp -r $(@D) $(@D)/../_run
	rm -f $(@D)/*
	cp $(@D)/../_run/sam.std $(@D)/sam.std
	cp $(@D)/../_run/sam.par $(@D)/sam.par
	cp $(@D)/../_run/sam.cor $(@D)/sam.cor
	cp $(@D)/../_run/program.log $(@D)/program.log
	rm -rf $(@D)/../_run

updatechecks: $(checkfiles)
$(checkfiles): $(casefiles)
	cd $(@D); cp ../run/sam.std .

check: $(checks)
$(checks): $(casefiles)
	echo 'f1<-readLines("$(@D)/sam.std"); f2<-readLines("$(@D)/../run/sam.std"); identical(f1,f2)' | R --slave
	touch $(@)
